﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using System.Data;


namespace Trig_AMJ_HR_Forms
{
    class SPHelper : Trig_WF
    {

        string ErrorMsgs;
        Demand_Voucher_FormClass objDemand = new Demand_Voucher_FormClass();
        /// <summary>
        /// Generate Request No based on Doc Prefix and Starting No for Master List.
        /// </summary>
        /// <param name="mainLstName"></param>
        /// <param name="lblTxkNo"></param>
        /// <param name="SiteURL"></param>

        #region "IT Forms Auto No Generation"

        public void AutoNoGeneration(string mainLstName, string docTypeLstName, Label requestNo, string SiteURL)
        {
            try
            {
                SPListItem oLstItem = null;
                string RefNo;
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        SPList oList = oWeb.Lists.TryGetList(docTypeLstName);
                        if (oList != null)
                        {
                            // Get starting number from Document Types 
                            oLstItem = GetSPListItem(mainLstName, oList); // Check Master list is in Document Types or not
                            if (oLstItem != null)
                            {
                                int stNo = Convert.ToInt32(oLstItem["Starting Number"]) + 1;
                                RefNo = oLstItem["DocPrefix"] + "/" + DateTime.Now.Year + "/" + Convert.ToString(stNo);
                                requestNo.Text = RefNo;
                                // Update starting number for Document Types 
                                int itmID = Convert.ToInt32(oLstItem["ID"]);
                                SPListItem oLstItemUpt = oList.GetItemById(itmID);
                                oLstItemUpt["Starting Number"] = stNo;
                                oLstItemUpt.Update();
                            }
                            else { RefNo = null; requestNo.Text = null; }
                        }
                        oWeb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "AutoNoGeneration";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");

            }

        }

        #endregion

        /// <summary>
        /// Get User Profiles and assign values to controls for OnBehalf of users
        /// </summary>
        /// <param name="AccountName"></param>
        /// <param name="name"></param>
        /// <param name="id"></param>
        /// <param name="dept"></param>
        /// <param name="position"></param>
        /// <param name="mob"></param>

        #region "Get User Profiles"

        public void GetCurrentUserDetails(string AccountName, TextBox name, TextBox id, TextBox division, TextBox designation, TextBox mob, TextBox DOJ, TextBox passportno,
            TextBox passexpire, TextBox qatarid, TextBox qataridexpire, TextBox nationality)
        {
            try
            {
                id.Text = null; division.Text = null; designation.Text = null; mob.Text = null; DOJ.Text = null; passportno.Text = null;
                passexpire.Text = null; qatarid.Text = null; qataridexpire.Text = null;

                UserProfile userProfile = GetUserInfo(AccountName);

                if (userProfile[PropertyConstants.FirstName].Value != null)
                {
                    if (name != null)
                        name.Text = userProfile[PropertyConstants.FirstName].Value.ToString();
                }

                checkField(userProfile, id, "EmployeeID");
                checkField(userProfile, division, "Division");
                checkField(userProfile, designation, "Designation");
                checkField(userProfile, mob, "CellPhone");

                checkField(userProfile, DOJ, "DOJ");
                if (DOJ.Text == "NA") DOJ.Text = DOJ.Text; else DOJ.Text = DateTime.Parse(DOJ.Text).ToString("dd/MM/yyyy");

                checkField(userProfile, passportno, "PassportNo");

                checkField(userProfile, passexpire, "PassportExpireOn");
                if (passexpire.Text == "NA") passexpire.Text = passexpire.Text; else passexpire.Text = DateTime.Parse(passexpire.Text).ToString("dd/MM/yyyy");

                checkField(userProfile, qatarid, "QatarID");

                checkField(userProfile, qataridexpire, "QatarIDExpireOn");
                if (qataridexpire.Text == "NA") qataridexpire.Text = qataridexpire.Text; else qataridexpire.Text = DateTime.Parse(qataridexpire.Text).ToString("dd/MM/yyyy");

                checkField(userProfile, nationality, "Nationality");

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "GetCurrentUserDetails";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        public void GetCurrentUserDetails(string AccountName, TextBox id, TextBox division, TextBox department, TextBox designation, TextBox mob)
        {
            try
            {
                UserProfile userProfile = GetUserInfo(AccountName);

                checkField(userProfile, id, "EmployeeID");
                checkField(userProfile, division, "Division");
                checkField(userProfile, designation, "Designation");
                checkField(userProfile, department, "Department");
                checkField(userProfile, mob, "CellPhone");

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "GetCurrentUserDetails";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        public void GetCurrentUserDetails(string AccountName, Label nationality, Label qatarID, DateTimeControl expireDt)
        {
            try
            {
                UserProfile userProfile = GetUserInfo(AccountName);

                checkField(userProfile, nationality, "Nationality");
                checkField(userProfile, qatarID, "QatarID");
                checkField(userProfile, expireDt, "QatarIDExpireOn");


            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "GetCurrentUserDetails";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        public UserProfile GetUserInfo(string AccountName)
        {
            UserProfile profile = null;
            SPServiceContext serviceContext = SPServiceContext.Current;
            UserProfileManager profileManager = new UserProfileManager(serviceContext);
            if (AccountName != string.Empty)
            {
                profile = profileManager.GetUserProfile(AccountName);
            }
            else
            {
                profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
            }
            return profile;
        }


        /// <summary>
        /// To check the properties is in SharePoint User Profile and assign values to controls
        /// </summary>
        /// <param name="userProfile"></param>
        /// <param name="fieldName"></param>
        /// <param name="propertyName"></param>
        #region "Check Fields"

        public void checkField(UserProfile userProfile, Label fieldName, string propertyName)
        {
            try
            {
                if (userProfile[propertyName].Value != null)
                    fieldName.Text = userProfile[propertyName].Value.ToString();
                else
                    fieldName.Text = "NA";

            }
            catch (Exception)
            {

            }
        }

        public void checkField(UserProfile userProfile, TextBox fieldName, string propertyName)
        {
            try
            {
                if (userProfile[propertyName].Value != null)
                    fieldName.Text = userProfile[propertyName].Value.ToString();
                else
                    fieldName.Text = "NA";

            }
            catch (Exception)
            {

            }
        }

        public void checkField(UserProfile userProfile, DateTimeControl fieldName, string propertyName)
        {
            try
            {
                if (userProfile[propertyName].Value != null)
                    fieldName.SelectedDate = Convert.ToDateTime(userProfile[propertyName].Value);

            }
            catch (Exception)
            {

            }
        }

        #endregion

        #endregion


        /// <summary>
        /// Get Workflow current order
        /// </summary>
        /// <param name="SiteURL"></param>
        /// <param name="TaskLstName"></param>
        /// <param name="refNo"></param>
        /// <returns></returns>
        public int GetCurrentWFOrder(string SiteURL, string TaskLstName, string refNo)
        {

            SPListItem tskItems = null;
            int wfCnt = 0;
            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPQuery qry = new SPQuery();
                    string CamlQry;
                    CamlQry = "<Where><And><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq><Eq>" +
                        "<FieldRef Name=\"Status\" /><Value Type=\"Choice\">Not Started</Value></Eq></And></Where>";
                    qry.ViewFields = "<FieldRef Name='WFCurrentOrder' />";
                    tskItems = GetSPListItem(SiteURL, TaskLstName, CamlQry);
                    if (tskItems != null)
                        wfCnt = Convert.ToInt32(tskItems["WFCurrentOrder"]);
                }
            }
            return wfCnt;
        }


        #region "Add Leave Request Details on Form"

        public string AddLeaveItems(string SiteURL, string MainLstName, string TaskLstName, string CmntsLstName, int onBehalf, string attLibName, FileUpload fileUploadControl, string WorkflowConfigList,
          PeopleEditor pplcnt, params object[] cntrls)
        {
            string lstGuid = null;
            string refNo = (cntrls[0] as string);
            SPWeb oWeb = null;
            SPList oListMain = null; SPList oListTask = null;
            SPFieldUserValue UserName = null;
            #region "Add Items in forms"

            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        oListMain = oWeb.Lists.TryGetList(MainLstName);
                        oListTask = oWeb.Lists.TryGetList(TaskLstName);
                        if (oListMain != null)
                        {
                            SPListItem oLstItem = oListMain.Items.Add();

                            oLstItem["Title"] = refNo; // (cntrls[0] as string);
                            oLstItem["Reference Number"] = refNo; // (cntrls[0] as string);

                            string ReqDt = (cntrls[1] as string);
                            //DateTime ReqDts = DateTime.ParseExact(ReqDt, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
                            //oLstItem["DateofEmployment"] = Convert.ToDateTime(ReqDt);

                            oLstItem["RequestDate"] = Convert.ToDateTime((cntrls[1] as string));
                            oLstItem["Document Status"] = "In Progress";



                            SPUser User = oWeb.EnsureUser((cntrls[2] as string).ToLower()); //oWeb.SiteUsers[(cntrls[2] as string)];
                            UserName = new SPFieldUserValue(oWeb, User.ID, User.Name);

                            oLstItem["RequestedBy"] = UserName;
                            oLstItem["LoggedinID"] = (cntrls[3] as string);
                            oLstItem["LoggedinDivision"] = (cntrls[4] as string);
                            oLstItem["LoggedinDepartment"] = (cntrls[28] as string);
                            oLstItem["LoggedinDesignation"] = (cntrls[5] as string);
                            oLstItem["LoggedinMobileNo"] = (cntrls[6] as string);

                            if (onBehalf == 0)
                            {
                                oLstItem["SubmittedFor"] = UserName;// (cntrls[2] as string);
                                oLstItem["EmployeeID"] = (cntrls[3] as string);
                                oLstItem["Division"] = (cntrls[4] as string);
                                oLstItem["Department"] = (cntrls[28] as string);
                                oLstItem["Designation"] = (cntrls[5] as string);
                                oLstItem["MobileNo"] = (cntrls[6] as string);
                            }
                            else
                            {

                                SPUser Users = oWeb.EnsureUser((cntrls[7] as string).ToLower()); //oWeb.SiteUsers[(cntrls[7] as string)];
                                SPFieldUserValue UserNames = new SPFieldUserValue(oWeb, Users.ID, Users.Name);

                                oLstItem["SubmittedFor"] = UserNames;//Convert.ToString(str1[10]);
                                oLstItem["EmployeeID"] = (cntrls[8] as string);
                                oLstItem["Division"] = (cntrls[9] as string);
                                oLstItem["Department"] = (cntrls[29] as string);
                                oLstItem["Designation"] = (cntrls[10] as string);
                                oLstItem["MobileNo"] = (cntrls[11] as string);

                            }
                            oLstItem["Nationality"] = (cntrls[12] as string);
                            oLstItem["LeaveType"] = (cntrls[13] as string);

                            DateTime travelDt = Convert.ToDateTime(cntrls[14]);
                            DateTime returnDt = Convert.ToDateTime(cntrls[15]);
                            int leaveDays = (int)(returnDt - travelDt).TotalDays;
                            leaveDays++;

                            oLstItem["TravelDate"] = (cntrls[14] as string);
                            oLstItem["ReturnDate"] = (cntrls[15] as string);
                            oLstItem["LeaveDays"] = leaveDays;
                            //oLstItem["WorkEndorsedto"] = (cntrls[17] as string);
                            oLstItem["VacationEligibility"] = (cntrls[18] as string);
                            if (onBehalf == 0)
                                oLstItem["OnBehalfof"] = "No";
                            else
                                oLstItem["OnBehalfof"] = "Yes";
                            oLstItem["HandoverStatus"] = "No";
                            oLstItem["ExitStatus"] = "No";
                            oLstItem["ResumptionStatus"] = "No";
                            oLstItem["AirticketBornebyEmployee"] = (cntrls[19] as string);

                            if ((cntrls[19] as string) == "Yes") oLstItem["TicketPaidBy"] = "Employee"; else oLstItem["TicketPaidBy"] = "Company";

                            if (!string.IsNullOrEmpty((cntrls[21] as string)) && (cntrls[21] as string) != "NA")
                            {
                                string dtJoining = (cntrls[21] as string);
                                DateTime dojs = DateTime.ParseExact(dtJoining, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
                                oLstItem["DateofEmployment"] = dojs;
                            }
                            oLstItem["YearofExperience"] = (cntrls[22] as string);

                            oLstItem["PassportNo"] = (cntrls[23] as string);

                            if (!string.IsNullOrEmpty((cntrls[24] as string)) && (cntrls[24] as string) != "NA")
                            {
                                string passExp = (cntrls[24] as string);
                                DateTime passExpiry = DateTime.ParseExact(passExp, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
                                oLstItem["PassportExpiryOn"] = passExpiry;
                            }

                            //DateTime QatarIDExpire = Convert.ToDateTime(cntrls[26] as string);
                            oLstItem["QatarID"] = (cntrls[25] as string);

                            if (!string.IsNullOrEmpty((cntrls[26] as string)) && (cntrls[26] as string) != "NA")
                            {
                                string qatarEap = (cntrls[26] as string);
                                DateTime qatarExpiry = DateTime.ParseExact(qatarEap, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
                                oLstItem["QatarIDExpireOn"] = qatarExpiry;
                            }
                            oLstItem["LeaveOthers"] = (cntrls[27] as string);



                            oLstItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                            lstGuid = Convert.ToString(oListMain.ID);
                        }
                        else
                        {
                            GenerateExceptionLog("Trig_AMJ_HR_Forms :: Leave Request Forms :: SaveFormDetails", "List does not exist", "AddLeaveItems");
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                ErrorMsgs = "Trig_AMJ_HR_Forms" + "::" + "SPHelper" + "::" + "AddLeaveRequestItems";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                //SetErrorLogs(SiteURL, "AddItems", ex.Message, ex.StackTrace);
            }

            #endregion

            if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                AddAttachement(SiteURL, attLibName, refNo, lstGuid, fileUploadControl);

            // Approval user and comments updation
            SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, UserName.LookupValue, (cntrls[20] as string), 0);

            string CurrentUser = SPContext.Current.Web.CurrentUser.Name;
            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);

            SPFieldUserValue ofldUserName = null;
            if (!string.IsNullOrEmpty(WFUser[1]))
            {
                ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
            }
            if (Convert.ToString(ofldUserName.User.Name.ToLower()) != CurrentUser.ToLower())
            {
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, UserName.LookupValue);
            }
            else
            {
                WFUser = new string[10];
                WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, true, CurrentUser, false, 0);
                if (!string.IsNullOrEmpty(WFUser[1]))
                {
                    ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                }
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, UserName.LookupValue);
            }
            return lstGuid;
        }

        #endregion


        #region "Add Undertaking Details on Form"

        public string AddUndertakinItems(string SiteURL, string MainLstName, string TaskLstName, string CmntsLstName, int onBehalf, string attLibName, FileUpload fileUploadControl, string WorkflowConfigList,
          PeopleEditor pplcnt, params object[] cntrls)
        {
            string lstGuid = null;
            string refNo = (cntrls[0] as string);
            SPWeb oWeb = null;
            SPList oListMain = null; SPList oListTask = null;
            SPFieldUserValue UserName = null;
            #region "Add Items in forms"

            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        oListMain = oWeb.Lists.TryGetList(MainLstName);
                        oListTask = oWeb.Lists.TryGetList(TaskLstName);
                        if (oListMain != null)
                        {
                            SPListItem oLstItem = oListMain.Items.Add();

                            oLstItem["Title"] = refNo; // (cntrls[0] as string);
                            oLstItem["Reference Number"] = refNo; // (cntrls[0] as string);

                            string ReqDt = (cntrls[1] as string);
                            //DateTime ReqDts = DateTime.ParseExact(ReqDt, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
                            //oLstItem["DateofEmployment"] = Convert.ToDateTime(ReqDt);

                            oLstItem["RequestDate"] = Convert.ToDateTime((cntrls[1] as string));
                            oLstItem["Document Status"] = "In Progress";



                            SPUser User = oWeb.EnsureUser((cntrls[2] as string)); //oWeb.SiteUsers[(cntrls[2] as string)];
                            UserName = new SPFieldUserValue(oWeb, User.ID, User.Name);

                            oLstItem["RequestedBy"] = UserName;
                            oLstItem["LoggedinID"] = (cntrls[3] as string);
                            oLstItem["LoggedinDivision"] = (cntrls[4] as string);
                            oLstItem["LoggedinDesignation"] = (cntrls[5] as string);
                            oLstItem["LoggedinMobileNo"] = (cntrls[6] as string);

                            if (onBehalf == 0)
                            {
                                oLstItem["SubmittedFor"] = UserName;// (cntrls[2] as string);
                                oLstItem["EmployeeID"] = (cntrls[3] as string);
                                oLstItem["Division"] = (cntrls[4] as string);
                                oLstItem["Designation"] = (cntrls[5] as string);
                                oLstItem["MobileNo"] = (cntrls[6] as string);
                            }
                            else
                            {

                                SPUser Users = oWeb.EnsureUser((cntrls[7] as string)); //oWeb.SiteUsers[(cntrls[7] as string)];
                                SPFieldUserValue UserNames = new SPFieldUserValue(oWeb, Users.ID, Users.Name);

                                oLstItem["SubmittedFor"] = UserNames;//Convert.ToString(str1[10]);
                                oLstItem["EmployeeID"] = (cntrls[8] as string);
                                oLstItem["Division"] = (cntrls[9] as string);
                                oLstItem["Designation"] = (cntrls[10] as string);
                                oLstItem["MobileNo"] = (cntrls[11] as string);

                            }

                            oLstItem["LeaveReferenceNo"] = (cntrls[13] as string);
                            oLstItem["LeaveRequestDate"] = Convert.ToDateTime((cntrls[14] as string));

                            oLstItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                            lstGuid = Convert.ToString(oListMain.ID);
                        }
                        else
                        {
                            GenerateExceptionLog("Trig_AMJ_HR_Forms :: Undertaking Forms :: SaveFormDetails", "List does not exist", "AddUndertakinItems");
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                ErrorMsgs = "Trig_AMJ_HR_Forms" + "::" + "SPHelper" + "::" + "AddUndertakingItems";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                //SetErrorLogs(SiteURL, "AddItems", ex.Message, ex.StackTrace);
            }

            #endregion

            if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                AddAttachement(SiteURL, attLibName, refNo, lstGuid, fileUploadControl);

            // Approval user and comments updation
            SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, UserName.LookupValue, (cntrls[12] as string), 0);

            string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;
            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);

            SPFieldUserValue ofldUserName = null;
            if (!string.IsNullOrEmpty(WFUser[1]))
            {
                ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
            }
            if (Convert.ToString(WFUser[1]) != CurrentUser)
            {
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, UserName.LookupValue);
            }
            else
            {
                WFUser = new string[10];
                WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, true, CurrentUser, false, 0);
                if (!string.IsNullOrEmpty(WFUser[1]))
                {
                    ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                }
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, UserName.LookupValue);
            }
            return lstGuid;
        }

        #endregion


        #region "Add HR Details on Form"

        public string AddHR_RequestItems(string SiteURL, string MainLstName, string TaskLstName, string CmntsLstName, string attLibName, FileUpload fileUploadControl, string WorkflowConfigList,
          PeopleEditor pplcnt, params object[] cntrls)
        {
            string lstGuid = null;
            string refNo = (cntrls[0] as string);
            SPWeb oWeb = null;
            SPList oListMain = null; SPList oListTask = null;
            SPFieldUserValue RequestBy = null;
            SPFieldUserValue SubmittedFor = null;
            #region "Add Items in forms"

            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        oListMain = oWeb.Lists.TryGetList(MainLstName);
                        oListTask = oWeb.Lists.TryGetList(TaskLstName);
                        if (oListMain != null)
                        {
                            SPListItem oLstItem = oListMain.Items.Add();

                            oLstItem["Title"] = refNo; // (cntrls[0] as string);
                            oLstItem["Reference Number"] = refNo; // (cntrls[0] as string);
                            string ReqDt = (cntrls[1] as string);
                            oLstItem["RequestDate"] = ((System.DateTime)(cntrls[1])).Date;
                            oLstItem["Document Status"] = "In Progress";

                            oLstItem["RequestType"] = (cntrls[2] as string);


                            SPUser User = oWeb.EnsureUser((cntrls[3] as string).ToLower()); //oWeb.SiteUsers[(cntrls[3] as string)];
                            RequestBy = new SPFieldUserValue(oWeb, User.ID, User.Name);

                            oLstItem["RequestedBy"] = RequestBy;

                            object oj = (object[])(cntrls[4]);
                            if (cntrls[4] != null)
                            {
                                //oWeb.EnsureUser(Convert.ToString(((object[])(oj))[0]));
                                SPUser SUser = oWeb.EnsureUser(Convert.ToString(((object[])(oj))[0]));// oWeb.SiteUsers[Convert.ToString(((object[])(oj))[0])];
                                SubmittedFor = new SPFieldUserValue(oWeb, SUser.ID, SUser.Name);
                                oLstItem["SubmittedFor"] = SubmittedFor;
                                oLstItem["EmployeeID"] = Convert.ToString(((object[])(oj))[1]);
                                oLstItem["Division"] = Convert.ToString(((object[])(oj))[2]);
                                oLstItem["Designation"] = Convert.ToString(((object[])(oj))[3]);
                                oLstItem["Nationality"] = Convert.ToString(((object[])(oj))[4]);
                                oLstItem["SponsorNo"] = Convert.ToString(((object[])(oj))[5]);
                                oLstItem["SponsorshipBranch"] = Convert.ToString(((object[])(oj))[6]);
                                oLstItem["TravelDate"] = ((System.DateTime)(((object[])(oj))[7])).Date;
                                oLstItem["ReturnDate"] = ((System.DateTime)(((object[])(oj))[8])).Date;
                                oLstItem["LeaveReferenceNo"] = Convert.ToString(((object[])(oj))[9]);
                                oLstItem["LeaveRequestDate"] = ((System.DateTime)(((object[])(oj))[10])).Date;
                            }

                            oLstItem["Reason"] = (cntrls[5] as string);

                            oLstItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                            lstGuid = Convert.ToString(oListMain.ID);
                        }
                        else
                        {
                            GenerateExceptionLog("Trig_AMJ_HR_Forms :: Leave Request Forms :: SaveFormDetails", "List does not exist", "AddLeaveItems");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + "::" + "SPHelper" + "::" + "AddLeaveRequestItems";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            #endregion

            if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                AddAttachement(SiteURL, attLibName, refNo, lstGuid, fileUploadControl);

            // Approval user and comments updation
            SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, RequestBy.LookupValue, (cntrls[6] as string), 0);

            string CurrentUser = SPContext.Current.Web.CurrentUser.Name;
            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);

            SPFieldUserValue ofldUserName = null;
            if (!string.IsNullOrEmpty(WFUser[1]))
            {
                ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
            }
            if (Convert.ToString(ofldUserName.User.Name.ToLower()) != CurrentUser.ToLower())
            {
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], 2, null);
            }
            else
            {
                WFUser = new string[10];
                WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, true, CurrentUser, false, 0);
                if (!string.IsNullOrEmpty(WFUser[1]))
                {
                    ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                }
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], 2, null);
            }


            return lstGuid;
        }

        #endregion


        #region "Add Resumption Details on Form"

        public string AddResumption_Items(string SiteURL, string MainLstName, string TaskLstName, string CmntsLstName, string attLibName, FileUpload fileUploadControl, string WorkflowConfigList,
          PeopleEditor pplcnt, params object[] cntrls)
        {
            string lstGuid = null;
            string refNo = (cntrls[0] as string);
            SPWeb oWeb = null;
            SPList oListMain = null; SPList oListTask = null;
            SPFieldUserValue RequestBy = null;
            SPFieldUserValue SubmittedFor = null;
            #region "Add Items in forms"

            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        oListMain = oWeb.Lists.TryGetList(MainLstName);
                        oListTask = oWeb.Lists.TryGetList(TaskLstName);
                        if (oListMain != null)
                        {
                            SPListItem oLstItem = oListMain.Items.Add();

                            oLstItem["Title"] = refNo; // (cntrls[0] as string);
                            oLstItem["Reference Number"] = refNo; // (cntrls[0] as string);
                            string ReqDt = (cntrls[1] as string);
                            oLstItem["RequestDate"] = ((System.DateTime)(cntrls[1])).Date;
                            oLstItem["Document Status"] = "In Progress";
                            SPUser User = oWeb.EnsureUser((cntrls[2] as string).ToLower());//oWeb.SiteUsers[(cntrls[2] as string)];
                            RequestBy = new SPFieldUserValue(oWeb, User.ID, User.Name);
                            oLstItem["RequestedBy"] = RequestBy;

                            object oj = (object[])(cntrls[3]);
                            if (cntrls[3] != null)
                            {
                                oLstItem["LeaveReferenceNo"] = Convert.ToString(((object[])(oj))[0]);
                                oLstItem["LeaveRequestDate"] = ((System.DateTime)(((object[])(oj))[1])).Date;
                                SPUser SUser = oWeb.EnsureUser(Convert.ToString(((object[])(oj))[2]));//oWeb.SiteUsers[Convert.ToString(((object[])(oj))[2])];
                                SubmittedFor = new SPFieldUserValue(oWeb, SUser.ID, SUser.Name);
                                oLstItem["SubmittedFor"] = SubmittedFor;

                                oLstItem["EmployeeID"] = Convert.ToString(((object[])(oj))[3]);
                                oLstItem["Division"] = Convert.ToString(((object[])(oj))[4]);
                                oLstItem["Designation"] = Convert.ToString(((object[])(oj))[5]);
                                oLstItem["PassportNo"] = Convert.ToString(((object[])(oj))[6]);

                                oLstItem["LeaveType"] = Convert.ToString(((object[])(oj))[7]);
                                oLstItem["TravelDate"] = ((System.DateTime)(((object[])(oj))[8])).Date;
                                oLstItem["ReturnDate"] = ((System.DateTime)(((object[])(oj))[9])).Date;
                                oLstItem["ResumptionDate"] = ((System.DateTime)(((object[])(oj))[10])).Date;
                                oLstItem["ExcessLeaveDays"] = Convert.ToInt32(((object[])(oj))[11]);
                                oLstItem["Action"] = Convert.ToString(((object[])(oj))[12]);
                                oLstItem["Department"] = Convert.ToString(((object[])(oj))[13]);
                            }

                            oLstItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                            lstGuid = Convert.ToString(oListMain.ID);
                        }
                        else
                        {
                            GenerateExceptionLog("Trig_AMJ_HR_Forms :: Resumption of Duty :: SaveFormDetails", "List does not exist", "AddResumption_Items");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + "::" + "SPHelper" + "::" + "AddResumption_Items";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            #endregion

            if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                AddAttachement(SiteURL, attLibName, refNo, lstGuid, fileUploadControl);

            // Approval user and comments updation
            SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, RequestBy.LookupValue, (cntrls[4] as string), 0);

            string CurrentUser = SPContext.Current.Web.CurrentUser.Name;
            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);

            SPFieldUserValue ofldUserName = null;
            if (!string.IsNullOrEmpty(WFUser[1]))
            {
                ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                if (Convert.ToString(ofldUserName.User.Name.ToLower()) != CurrentUser.ToLower())
                {
                    createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], 2, null);
                }
            }
            //if (Convert.ToString(ofldUserName.User.Name.ToLower()) != CurrentUser.ToLower())
            //{
            //    createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], 2, null);
            //}
            else
            {
                WFUser = new string[10];
                WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, true, CurrentUser, false, 0);
                if (!string.IsNullOrEmpty(WFUser[1]))
                {
                    ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                }
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], 2, null);
            }


            return lstGuid;
        }

        #endregion


        #region "Add Clearance Details on Form"

        public string AddClearance_Items(string SiteURL, string MainLstName, string TaskLstName, string CmntsLstName, string attLibName, FileUpload fileUploadControl, string WorkflowConfigList,
          PeopleEditor pplcnt, params object[] cntrls)
        {
            string lstGuid = null;
            string refNo = (cntrls[0] as string);
            SPWeb oWeb = null;
            SPList oListMain = null; SPList oListTask = null;
            SPFieldUserValue RequestBy = null;
            SPFieldUserValue SubmittedFor = null;
            #region "Add Items in forms"

            string division = "";

            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        oListMain = oWeb.Lists.TryGetList(MainLstName);
                        oListTask = oWeb.Lists.TryGetList(TaskLstName);
                        if (oListMain != null)
                        {
                            SPListItem oLstItem = oListMain.Items.Add();
                            oLstItem["Title"] = refNo;
                            oLstItem["Reference Number"] = refNo;
                            string ReqDt = (cntrls[1] as string);
                            oLstItem["RequestDate"] = ((System.DateTime)(cntrls[1])).Date;

                            oLstItem["Document Status"] = "In Progress";

                            oLstItem["LeaveReferenceNo"] = (cntrls[2] as string) == "" ? "" : (cntrls[2] as string);

                            if (!string.IsNullOrEmpty(cntrls[2] as string))
                            {
                                //if (!string.IsNullOrEmpty(Convert.ToString((System.DateTime)(cntrls[3]))))
                                oLstItem["LeaveRequestDate"] = ((System.DateTime)(cntrls[3])).Date;
                                oLstItem["TravelDateDate"] = ((System.DateTime)(cntrls[14])).Date;
                                oLstItem["ReturnDate"] = ((System.DateTime)(cntrls[15])).Date;

                            }

                            SPUser User = oWeb.EnsureUser((cntrls[4] as string).ToLower()); //oWeb.SiteUsers[(cntrls[4] as string)];
                            SubmittedFor = new SPFieldUserValue(oWeb, User.ID, User.Name);

                            oLstItem["SubmittedFor"] = SubmittedFor;
                            oLstItem["EmployeeID"] = (cntrls[5] as string);

                            oLstItem["Division"] = (cntrls[6] as string);

                            division = (cntrls[6] as string);

                            oLstItem["Department"] = (cntrls[13] as string);

                            oLstItem["Designation"] = (cntrls[7] as string);
                            oLstItem["ClearanceType"] = (cntrls[8] as string);

                            oLstItem["EffectineOn"] = ((System.DateTime)(cntrls[9])).Date;


                            SPUser User1 = oWeb.EnsureUser((cntrls[10] as string).ToLower());//oWeb.SiteUsers[(cntrls[10] as string)];
                            RequestBy = new SPFieldUserValue(oWeb, User1.ID, User1.Name);
                            oLstItem["RequestedBy"] = RequestBy;



                            oLstItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                            lstGuid = Convert.ToString(oListMain.ID);
                        }
                        else
                        {
                            GenerateExceptionLog("Trig_AMJ_HR_Forms :: Resumption of Duty :: SaveFormDetails", "List does not exist", "AddResumption_Items");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + "::" + "SPHelper" + "::" + "AddResumption_Items";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            #endregion

            if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                AddAttachement(SiteURL, attLibName, refNo, lstGuid, fileUploadControl);

            // Approval user and comments updation
            SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, RequestBy.LookupValue, (cntrls[12] as string), 0);

            string CurrentUser = SPContext.Current.Web.CurrentUser.Name;
            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);

            SPFieldUserValue ofldUserName = null;
            if (!string.IsNullOrEmpty(WFUser[1]))
            {

                ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);

                if (Convert.ToString(ofldUserName.User.Name.ToLower()) != CurrentUser.ToLower())
                {
                    createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], 2, null, division, null);
                }
            }
            else
            {
                WFUser = new string[10];
                WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);
                if (!string.IsNullOrEmpty(WFUser[1]))
                {
                    ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                }
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false,
                    WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], 2, null, division, null);
            }




            return lstGuid;
        }

        #endregion


        #region "Personnel Action Form"

        public string AddPersonnelAction_Items(string SiteURL, string MainLstName, string TaskLstName, string CmntsLstName, string attLibName, FileUpload fileUploadControl, string WorkflowConfigList,
          PeopleEditor pplcnt, params object[] cntrls)
        {
            string lstGuid = null;
            string refNo = (cntrls[0] as string);
            SPWeb oWeb = null;
            SPList oListMain = null; SPList oListTask = null;
            SPFieldUserValue RequestBy = null;
            SPFieldUserValue SubmittedFor = null;
            #region "Add Items in forms"

            string division = "";

            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        oListMain = oWeb.Lists.TryGetList(MainLstName);
                        oListTask = oWeb.Lists.TryGetList(TaskLstName);
                        if (oListMain != null)
                        {
                            SPListItem oLstItem = oListMain.Items.Add();
                            oLstItem["Title"] = refNo;
                            oLstItem["Reference Number"] = refNo;
                            string ReqDt = (cntrls[1] as string);
                            oLstItem["RequestDate"] = ((System.DateTime)(cntrls[1])).Date;

                            oLstItem["Document_x0020_Status"] = "In Progress";
                            oLstItem["Name"] = (cntrls[2] as string);
                            oLstItem["Nationality"] = (cntrls[3] as string);


                            SPUser User = oWeb.EnsureUser((cntrls[21] as string).ToLower()); //oWeb.SiteUsers[(cntrls[21] as string)];
                            SubmittedFor = new SPFieldUserValue(oWeb, User.ID, User.Name);
                            oLstItem["SubmittedFor"] = SubmittedFor;

                            oLstItem["EmployeeID"] = (cntrls[4] as string);
                            oLstItem["DOB"] = ((System.DateTime)(cntrls[5])).Date;
                            oLstItem["MaritalStatus"] = (cntrls[6] as string);
                            oLstItem["FathersName"] = (cntrls[7] as string);
                            oLstItem["NoDependants"] = (cntrls[8] as string);
                            oLstItem["Address"] = (cntrls[9] as string);
                            oLstItem["MobileNo"] = (cntrls[10] as string);
                            oLstItem["PassportNo"] = (cntrls[11] as string);
                            oLstItem["PassportExpiryOn"] = ((System.DateTime)(cntrls[12])).Date;
                            oLstItem["DateofEmployment"] = (((System.DateTime)(cntrls[13]))).Date;
                            oLstItem["QatarID"] = (cntrls[14] as string);
                            oLstItem["ResidentPermitValidity"] = ((System.DateTime)(cntrls[15])).Date;
                            oLstItem["ActionType"] = (cntrls[16] as string);
                            oLstItem["ActionOthers"] = (cntrls[17] as string);


                            SPUser User1 = oWeb.EnsureUser((cntrls[18] as string).ToLower()); //oWeb.SiteUsers[(cntrls[18] as string)];
                            RequestBy = new SPFieldUserValue(oWeb, User1.ID, User1.Name);
                            oLstItem["RequestedBy"] = RequestBy;

                            oLstItem["Division"] = (cntrls[18] as string);
                            oLstItem["Designation"] = (cntrls[19] as string);

                            oLstItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                            lstGuid = Convert.ToString(oListMain.ID);
                        }
                        else
                        {
                            GenerateExceptionLog("Trig_AMJ_HR_Forms :: Resumption of Duty :: SaveFormDetails", "List does not exist", "AddResumption_Items");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + "::" + "SPHelper" + "::" + "AddResumption_Items";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            #endregion

            if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                AddAttachement(SiteURL, attLibName, refNo, lstGuid, fileUploadControl);

            // Approval user and comments updation
            SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, RequestBy.LookupValue, (cntrls[22] as string), 0);

            string CurrentUser = SPContext.Current.Web.CurrentUser.Name;
            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);
            SPFieldUserValue ofldUserName = null;
            string UserName = string.Empty;
            if (!string.IsNullOrEmpty(WFUser[1]))
            {
                ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                UserName = ofldUserName.User.Name.ToLower();
            }
            if (UserName != CurrentUser.ToLower())
            {
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], 1, null);
            }
            else
            {
                WFUser = new string[10];
                WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, true, CurrentUser, false, 0);
                if (!string.IsNullOrEmpty(WFUser[1]))
                {
                    ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                }
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], 1, null);
            }

            return lstGuid;
        }

        #endregion


        #region "Add Salary Advance Request Details on Form"

        public string AddSalAdv_RequestItems(string SiteURL, string MainLstName, string TaskLstName, string CmntsLstName, int onBehalf, string attLibName, FileUpload fileUploadControl, string WorkflowConfigList,
          PeopleEditor pplcnt, params object[] cntrls)
        {
            string lstGuid = null;
            string refNo = (cntrls[0] as string);
            SPWeb oWeb = null;
            SPList oListMain = null; SPList oListTask = null;
            SPFieldUserValue UserName = null;

            string submittedFor = string.Empty;
            #region "Add Items in forms"

            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        oListMain = oWeb.Lists.TryGetList(MainLstName);
                        oListTask = oWeb.Lists.TryGetList(TaskLstName);
                        if (oListMain != null)
                        {
                            SPListItem oLstItem = oListMain.Items.Add();

                            oLstItem["Title"] = refNo; // (cntrls[0] as string);
                            oLstItem["Reference Number"] = refNo; // (cntrls[0] as string);

                            string ReqDt = (cntrls[1] as string);
                            //DateTime ReqDts = DateTime.ParseExact(ReqDt, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
                            //oLstItem["DateofEmployment"] = Convert.ToDateTime(ReqDt);

                            oLstItem["RequestDate"] = Convert.ToDateTime((cntrls[1] as string));
                            oLstItem["Document Status"] = "In Progress";



                            SPUser User = oWeb.EnsureUser((cntrls[2] as string).ToLower()); //oWeb.SiteUsers[(cntrls[2] as string)];
                            UserName = new SPFieldUserValue(oWeb, User.ID, User.Name);

                            oLstItem["RequestedBy"] = UserName;
                            oLstItem["LoggedinID"] = (cntrls[3] as string);
                            oLstItem["LoggedinDivision"] = (cntrls[4] as string);
                            oLstItem["LoggedinDepartment"] = (cntrls[5] as string);
                            oLstItem["LoggedinDesignation"] = (cntrls[6] as string);
                            oLstItem["LoggedinMobileNo"] = (cntrls[7] as string);

                            if (onBehalf == 0)
                            {
                                oLstItem["SubmittedFor"] = UserName;// (cntrls[2] as string);
                                oLstItem["EmployeeID"] = (cntrls[3] as string);
                                oLstItem["Division"] = (cntrls[4] as string);
                                oLstItem["Department"] = (cntrls[5] as string);
                                oLstItem["Designation"] = (cntrls[6] as string);
                                //oLstItem["MobileNo"] = (cntrls[7] as string);
                                submittedFor = UserName.LookupValue;
                            }
                            else
                            {

                                SPUser Users = oWeb.EnsureUser((cntrls[8] as string).ToLower()); //oWeb.SiteUsers[(cntrls[8] as string)];
                                SPFieldUserValue UserNames = new SPFieldUserValue(oWeb, Users.ID, Users.Name);

                                oLstItem["SubmittedFor"] = UserNames;//Convert.ToString(str1[10]);
                                oLstItem["EmployeeID"] = (cntrls[9] as string);
                                oLstItem["Division"] = (cntrls[10] as string);
                                oLstItem["Department"] = (cntrls[11] as string);
                                oLstItem["Designation"] = (cntrls[12] as string);
                                //oLstItem["MobileNo"] = (cntrls[13] as string);
                                submittedFor = UserNames.LookupValue;

                            }

                            if (onBehalf == 0)
                                oLstItem["OnBehalfof"] = "No";
                            else
                                oLstItem["OnBehalfof"] = "Yes";

                            if (!string.IsNullOrEmpty((cntrls[14] as string)) && (cntrls[14] as string) != "NA")
                            {

                                DateTime doe = Convert.ToDateTime((cntrls[14] as string)); //DateTime.ParseExact(dtJoining, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
                                oLstItem["DateofEmployment"] = doe;
                            }

                            oLstItem["BasicSalary"] = Convert.ToDouble((cntrls[15] as string));
                            oLstItem["AdvanceAmount"] = Convert.ToDouble((cntrls[16] as string));
                            oLstItem["Instalment"] = Convert.ToInt32((cntrls[17] as string));
                            oLstItem["DeductionAmount"] = Convert.ToDouble((cntrls[18] as string));


                            if (!string.IsNullOrEmpty((cntrls[19] as string)) && (cntrls[19] as string) != "NA")
                            {
                                DateTime stDate = Convert.ToDateTime((cntrls[19] as string));
                                //DateTime stDt = DateTime.ParseExact(stDate, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
                                oLstItem["StartsOn"] = stDate;
                            }

                            if (!string.IsNullOrEmpty((cntrls[20] as string)) && (cntrls[20] as string) != "NA")
                            {
                                DateTime endDate = Convert.ToDateTime((cntrls[20] as string));
                                //DateTime endDt = DateTime.ParseExact(endDate, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
                                oLstItem["EndsOn"] = endDate;
                            }

                            oLstItem["OSAmount"] = (cntrls[21] as string);
                            oLstItem["TtlOSAmount"] = (cntrls[22] as string);

                            oLstItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                            lstGuid = Convert.ToString(oListMain.ID);
                        }
                        else
                        {
                            GenerateExceptionLog("Trig_AMJ_HR_Forms :: Leave Request Forms :: SaveFormDetails", "List does not exist", "AddLeaveItems");
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                ErrorMsgs = "Trig_AMJ_HR_Forms" + "::" + "SPHelper" + "::" + "AddLeaveRequestItems";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                //SetErrorLogs(SiteURL, "AddItems", ex.Message, ex.StackTrace);
            }

            #endregion

            if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                AddAttachement(SiteURL, attLibName, refNo, lstGuid, fileUploadControl);

            // Approval user and comments updation
            SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, UserName.LookupValue, (cntrls[23] as string), 0);

            string CurrentUser = SPContext.Current.Web.CurrentUser.Name;
            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);

            string userName = string.Empty;

            SPFieldUserValue ofldUserName = null;
            if (!string.IsNullOrEmpty(WFUser[1]))
            {
                ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                userName = ofldUserName.User.Name.ToLower();
            }
            if (userName != CurrentUser.ToLower())
            {
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, submittedFor);
            }
            else if (userName == CurrentUser.ToLower() || userName == "")
            {
                WFUser = new string[10];
                if (userName == "")
                {
                    WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);
                }
                else
                {
                    WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, true, CurrentUser, false, 0);
                }
                if (!string.IsNullOrEmpty(WFUser[1]))
                {
                    ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                }
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, submittedFor);
                //WFUser = new string[10];
                //WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, true, CurrentUser, false, 0);
                //if (!string.IsNullOrEmpty(WFUser[1]))
                //{
                //    ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                //}
                //createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, UserName.LookupValue);
            }
            return lstGuid;
        }

        #endregion


        #region "Add Qatar ID Request Details on Form"

        public string AddQatarID_RequestItems(string SiteURL, string MainLstName, string TaskLstName, string CmntsLstName, int onBehalf, string attLibName, FileUpload fileUploadControl, string WorkflowConfigList,
          PeopleEditor pplcnt, params object[] cntrls)
        {
            string lstGuid = null;
            string refNo = (cntrls[0] as string);
            SPWeb oWeb = null;
            SPList oListMain = null; SPList oListTask = null;
            SPFieldUserValue UserName = null;

            string submittedFor = string.Empty;
            #region "Add Items in forms"

            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        oListMain = oWeb.Lists.TryGetList(MainLstName);
                        oListTask = oWeb.Lists.TryGetList(TaskLstName);
                        if (oListMain != null)
                        {
                            SPListItem oLstItem = oListMain.Items.Add();

                            oLstItem["Title"] = refNo; // (cntrls[0] as string);
                            oLstItem["Reference Number"] = refNo; // (cntrls[0] as string);

                            string ReqDt = (cntrls[1] as string);
                            //DateTime ReqDts = DateTime.ParseExact(ReqDt, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
                            //oLstItem["DateofEmployment"] = Convert.ToDateTime(ReqDt);

                            oLstItem["RequestDate"] = Convert.ToDateTime((cntrls[1] as string));
                            oLstItem["Document Status"] = "In Progress";



                            SPUser User = oWeb.EnsureUser((cntrls[2] as string).ToLower()); //oWeb.SiteUsers[(cntrls[2] as string)];
                            UserName = new SPFieldUserValue(oWeb, User.ID, User.Name);
                            oLstItem["RequestedBy"] = UserName;

                            oLstItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                            lstGuid = Convert.ToString(oListMain.ID);
                        }
                        else
                        {
                            GenerateExceptionLog("Trig_AMJ_HR_Forms :: Leave Request Forms :: SaveFormDetails", "List does not exist", "AddLeaveItems");
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                ErrorMsgs = "Trig_AMJ_HR_Forms" + "::" + "SPHelper" + "::" + "AddLeaveRequestItems";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            #endregion

            if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                AddAttachement(SiteURL, attLibName, refNo, lstGuid, fileUploadControl);

            // Approval user and comments updation
            SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, UserName.LookupValue, (cntrls[3] as string), 0);

            string CurrentUser = SPContext.Current.Web.CurrentUser.Name;
            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);

            string userName = string.Empty;

            SPFieldUserValue ofldUserName = null;
            if (!string.IsNullOrEmpty(WFUser[1]))
            {
                ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                userName = ofldUserName.User.Name.ToLower();
            }
            if (userName != CurrentUser.ToLower())
            {
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, submittedFor);
            }
            else if (userName == CurrentUser.ToLower() || userName == "")
            {
                WFUser = new string[10];
                if (userName == "")
                {
                    WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, false, CurrentUser, false, 0);
                }
                else
                {
                    WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, true, CurrentUser, false, 0);
                }
                if (!string.IsNullOrEmpty(WFUser[1]))
                {
                    ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                }
                createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, submittedFor);
                //WFUser = new string[10];
                //WFUser = CheckCurrentUserAsWFUser(oWeb, WorkflowConfigList, MainLstName, true, CurrentUser, false, 0);
                //if (!string.IsNullOrEmpty(WFUser[1]))
                //{
                //    ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                //}
                //createTask(oWeb, oListMain, oListTask, WorkflowConfigList, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, UserName.LookupValue);
            }
            return lstGuid;
        }

        #endregion

        /// <summary>
        /// Add User and Approvers comments
        /// </summary>
        /// <param name="SiteURL"></param>
        /// <param name="cmntsLstName"></param>
        /// <param name="cntrls"></param>

        #region "Add User Comments Data"

        public void SetCommnets(string SiteURL, string cmntsLstName, params object[] cntrls)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            oWeb.AllowUnsafeUpdates = true;
                            SPList oList = oWeb.Lists.TryGetList(cmntsLstName);
                            if (oList != null)
                            {
                                SPListItem oLstItem = oList.Items.Add();
                                oLstItem["Title"] = (cntrls[0] as string);
                                oLstItem["Reference_x0020_Number"] = (cntrls[1] as string);
                                oLstItem["ListID"] = (cntrls[2] as string);
                                oLstItem["CommentByUser"] = (cntrls[3] as string);
                                oLstItem["User_x0020_Comments"] = (cntrls[4] as string);
                                oLstItem["WFCurrentOrder"] = Convert.ToInt32((cntrls[5] as string));
                                oWeb.AllowUnsafeUpdates = true;
                                oLstItem.Update();
                                oWeb.AllowUnsafeUpdates = false;
                            }

                            oWeb.AllowUnsafeUpdates = false;
                        }
                    }
                });

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "SetCommnets";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        #endregion


        /// <summary>
        /// Add Attachment to Attachment Libraty
        /// </summary>
        /// <param name="SiteUrl"></param>
        /// <param name="AttachmentsLibrary"></param>
        /// <param name="referenceNumber"></param>
        /// <param name="FormListID"></param>
        /// <param name="fileUploadControl"></param>

        #region "Add Attachment"

        private void AddAttachement(string SiteUrl, string AttachmentsLibrary, string referenceNumber, string FormListID, FileUpload fileUploadControl)
        {
            try
            {
                using (SPSite osite = new SPSite(SiteUrl))
                {
                    using (SPWeb oweb = osite.OpenWeb())
                    {
                        SPDocumentLibrary myLibrary = oweb.Lists[AttachmentsLibrary] as SPDocumentLibrary;
                        byte[] fileBytes = fileUploadControl.FileBytes;
                        string time = DateTime.Now.ToString().Replace("/", "");
                        string strDestUrl = myLibrary.RootFolder.Url + "/" + time.Replace(":", "") + fileUploadControl.FileName;
                        oweb.AllowUnsafeUpdates = true;
                        SPFile destFile = myLibrary.RootFolder.Files.Add(strDestUrl, fileBytes, true);
                        destFile.Item["ListID"] = FormListID;
                        destFile.Item["Reference_x0020_Number"] = referenceNumber;
                        SPUser ouser = oweb.EnsureUser(SPContext.Current.Web.CurrentUser.Name);
                        destFile.Item["UploadByUser"] = ouser;
                        destFile.Update();
                        destFile.Item.Update();
                        destFile.Update();
                        oweb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "AddAttachement";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        #endregion

        /// <summary>
        /// check current user configured in the Workflow config list as a first item of the DV form
        /// </summary>
        /// <param name="oweb"></param>
        /// <returns></returns>

        #region "CheckCurrentUserAsWFUser"

        public string[] CheckCurrentUserAsWFUser(SPWeb oweb, string WorkflowConfigList, string mainLstName, bool currentUserExist, string currentUser, bool approval, int WFCurrentOrder)
        {
            string[] orderNum = new string[10];
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (oweb.Lists.TryGetList(WorkflowConfigList) != null)
                    {
                        SPQuery oqry = new SPQuery();
                        if (currentUserExist)
                        {

                            oqry.Query = "<Where><And><Eq><FieldRef Name='Optional' /><Value Type='Boolean'>0</Value></Eq><And>"
                                + "<Neq><FieldRef Name='Send_x0020_to_x0020_Users' /><Value Type='User'>" + currentUser + "</Value></Neq><Eq><FieldRef Name='Doctype' />"
                                + "<Value Type='Lookup'>" + mainLstName + "</Value></Eq></And></And></Where>";
                        }
                        else if (approval)
                        {
                            oqry.Query = "<Where><And><Eq><FieldRef Name='Order0' /><Value Type='Number'>" + WFCurrentOrder + "</Value></Eq><Eq><FieldRef Name='Doctype' /><Value Type='Lookup'>" + mainLstName + "</Value></Eq></And></Where>";
                        }
                        else
                        {
                            oqry.Query = "<Where><Eq><FieldRef Name='Doctype' /><Value Type='Lookup'>" + mainLstName + "</Value></Eq></Where>";
                        }

                        if (oweb.Lists.TryGetList(WorkflowConfigList).GetItems(oqry).Count > 0)
                        {
                            SPListItem oitm = oweb.Lists.TryGetList(WorkflowConfigList).GetItems(oqry)[0];
                            orderNum[0] = Convert.ToString(oitm["Order0"]);
                            if (!string.IsNullOrEmpty(Convert.ToString(oitm["Send_x0020_to_x0020_Users"])))
                            {
                                SPFieldUserValue ofluser = new SPFieldUserValue(oweb, Convert.ToString(oitm["Send_x0020_to_x0020_Users"]));
                                orderNum[1] = Convert.ToString(ofluser);
                            }
                            orderNum[2] = Convert.ToBoolean(oitm["Optional"]).ToString();
                            orderNum[3] = Convert.ToString(oitm["Task_x0020_type"]);
                            orderNum[4] = Convert.ToString(oitm["UPAttributeName"]);
                            orderNum[5] = Convert.ToString(oitm["ECListName"]);
                            orderNum[6] = Convert.ToString(oitm["ECFieldName"]);
                            orderNum[7] = Convert.ToString(oitm["ECMatchField"]);
                            orderNum[8] = Convert.ToString(oitm["ECUPMatchField"]);
                        }
                        else if (currentUserExist)
                        {
                            oqry = new SPQuery();
                            oqry.Query = "<Where><And><IsNull><FieldRef Name='Send_x0020_to_x0020_Users' /></IsNull><Eq><FieldRef Name='Doctype' /><Value Type='Lookup'>" + mainLstName + "</Value></Eq></And></Where>";
                            if (oweb.Lists.TryGetList(WorkflowConfigList).GetItems(oqry).Count > 0)
                            {
                                SPListItem oitm = oweb.Lists.TryGetList(WorkflowConfigList).GetItems(oqry)[0];
                                orderNum[0] = Convert.ToString(oitm["Order0"]);
                                if (!string.IsNullOrEmpty(Convert.ToString(oitm["Send_x0020_to_x0020_Users"])))
                                {
                                    SPFieldUserValue ofluser = new SPFieldUserValue(oweb, Convert.ToString(oitm["Send_x0020_to_x0020_Users"]));
                                    orderNum[1] = Convert.ToString(ofluser);
                                }
                                orderNum[2] = Convert.ToBoolean(oitm["Optional"]).ToString();
                                orderNum[3] = Convert.ToString(oitm["Task_x0020_type"]);
                                orderNum[4] = Convert.ToString(oitm["UPAttributeName"]);
                                orderNum[5] = Convert.ToString(oitm["ECListName"]);
                                orderNum[6] = Convert.ToString(oitm["ECFieldName"]);
                                orderNum[7] = Convert.ToString(oitm["ECMatchField"]);
                                orderNum[8] = Convert.ToString(oitm["ECUPMatchField"]);
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "CheckCurrentUserAsWFUser";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            return orderNum;

        }

        #endregion

        /// <summary>
        /// Approve the form
        /// </summary>

        #region "Approve Form"

        public bool ApprovetheForm(string SiteURL, string MainLstName, string TaskLstName, string wfConfigLst, string CmntsLstName, string AttLibName, string FormID, string refNo,
            string TaskItemID, string WFTaskType, string ApprovalUser, string comments, FileUpload fileUploadControl, RadioButton rtbForwardOthers, RadioButton rtbSendBack,
            PeopleEditor pplcnt, bool AssignTosubmitUser, int onBehalf, string submittedFor)
        {

            bool formStatus = false;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {

                            SPList oLstTask = oWeb.Lists.TryGetList(TaskLstName);
                            SPList oLstForm = oWeb.Lists.TryGetList(MainLstName);
                            if (oLstTask != null && oLstForm != null)
                            {
                                FormID = Convert.ToString(oLstForm.ID);

                                if (!string.IsNullOrEmpty(TaskItemID))
                                {
                                    SPFieldUserValue ofldUser = null;
                                    if (rtbSendBack.Checked)
                                    {
                                        ofldUser = getSendBackUserfNametoAssignLabelText(oWeb, TaskLstName, refNo);
                                    }
                                    SPQuery updatecamQ = new SPQuery();
                                    updatecamQ.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + TaskItemID + "</Value></Eq></Where>";
                                    SPListItemCollection TasksListitemcoll = oLstTask.GetItems(updatecamQ);
                                    if (TasksListitemcoll.Count > 0)
                                    {
                                        SPListItem oitm = TasksListitemcoll[0];
                                        oitm["Status"] = "Completed";
                                        oitm["OutCome"] = "Approved";
                                        oWeb.AllowUnsafeUpdates = true;
                                        oitm.Update();
                                        oWeb.AllowUnsafeUpdates = false;
                                        WFTaskType = Convert.ToString(oitm["WFTaskType"]);
                                        int WFOrder = 0;
                                        WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]);

                                        SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, FormID, ApprovalUser, comments, WFOrder);

                                        if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                                            AddAttachement(SiteURL, AttLibName, refNo, FormID, fileUploadControl);


                                        if ((rtbForwardOthers.Checked && !string.IsNullOrEmpty(pplcnt.CommaSeparatedAccounts)) || rtbSendBack.Checked)
                                        {
                                            if (rtbForwardOthers.Checked)
                                            {
                                                createTask(oWeb, oLstForm, oLstTask, null, pplcnt, refNo, WFOrder, WFTaskType, true, false);
                                            }
                                            else if (rtbSendBack.Checked)
                                            {
                                                createTask(oWeb, oLstForm, oLstTask, ofldUser, pplcnt, refNo, WFOrder, WFTaskType, false, true);
                                            }
                                        }
                                        else
                                        {
                                            WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]) + 1;
                                            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, wfConfigLst, MainLstName, false, ApprovalUser, true, WFOrder);
                                            SPFieldUserValue ofldUserName = null;
                                            if (!string.IsNullOrEmpty(WFUser[1]))
                                            {
                                                ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                                            }
                                            createTask(oWeb, oLstForm, oLstTask, wfConfigLst, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false,
                                                WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, submittedFor);
                                            //}
                                        }
                                        if (objDemand.UpdateFormStatus(oWeb, wfConfigLst, MainLstName, refNo, WFOrder, false, rtbForwardOthers, rtbSendBack))
                                        {
                                            formStatus = true;
                                        }

                                    }
                                }
                                else
                                {
                                    GenerateExceptionLog("Trig_AMJ_HR_Forms:: Demand_Voucher_Form::ApprovetheForm", "Query string values is wrong", "task ID values is wrong or empty");
                                }
                            }
                        }
                    }

                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "ApprovetheForm";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            return formStatus;
        }

        #endregion


        /// <summary>
        /// Approve the form
        /// </summary>

        #region "Approve Form"

        public bool ApprovetheForm(string SiteURL, string MainLstName, string TaskLstName, string wfConfigLst, string CmntsLstName, string AttLibName, string FormID, string refNo,
            string TaskItemID, string WFTaskType, string ApprovalUser, string comments, FileUpload fileUploadControl, RadioButton rtbForwardOthers, RadioButton rtbSendBack,
            PeopleEditor pplcnt, bool AssignTosubmitUser, int onBehalf, string submittedFor, string divisionName, List<string> lstUsers)
        {

            bool formStatus = false;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {

                            SPList oLstTask = oWeb.Lists.TryGetList(TaskLstName);
                            SPList oLstForm = oWeb.Lists.TryGetList(MainLstName);
                            if (oLstTask != null && oLstForm != null)
                            {
                                FormID = Convert.ToString(oLstForm.ID);

                                if (!string.IsNullOrEmpty(TaskItemID))
                                {
                                    SPFieldUserValue ofldUser = null;
                                    if (rtbSendBack.Checked)
                                    {
                                        ofldUser = getSendBackUserfNametoAssignLabelText(oWeb, TaskLstName, refNo);
                                    }
                                    SPQuery updatecamQ = new SPQuery();
                                    updatecamQ.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + TaskItemID + "</Value></Eq></Where>";
                                    SPListItemCollection TasksListitemcoll = oLstTask.GetItems(updatecamQ);
                                    if (TasksListitemcoll.Count > 0)
                                    {
                                        SPListItem oitm = TasksListitemcoll[0];
                                        oitm["Status"] = "Completed";
                                        oitm["OutCome"] = "Approved";
                                        oWeb.AllowUnsafeUpdates = true;
                                        oitm.Update();
                                        oWeb.AllowUnsafeUpdates = false;
                                        WFTaskType = Convert.ToString(oitm["WFTaskType"]);
                                        int WFOrder = 0;
                                        WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]);

                                        SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, FormID, ApprovalUser, comments, WFOrder);

                                        if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                                            AddAttachement(SiteURL, AttLibName, refNo, FormID, fileUploadControl);


                                        if ((rtbForwardOthers.Checked && !string.IsNullOrEmpty(pplcnt.CommaSeparatedAccounts)) || rtbSendBack.Checked)
                                        {
                                            if (rtbForwardOthers.Checked)
                                            {
                                                createTask(oWeb, oLstForm, oLstTask, null, pplcnt, refNo, WFOrder, WFTaskType, true, false);
                                            }
                                            else if (rtbSendBack.Checked)
                                            {
                                                createTask(oWeb, oLstForm, oLstTask, ofldUser, pplcnt, refNo, WFOrder, WFTaskType, false, true);
                                            }
                                        }
                                        else
                                        {
                                            WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]) + 1;
                                            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, wfConfigLst, MainLstName, false, ApprovalUser, true, WFOrder);
                                            SPFieldUserValue ofldUserName = null;
                                            if (!string.IsNullOrEmpty(WFUser[1]))
                                            {
                                                ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                                            }
                                            createTask(oWeb, oLstForm, oLstTask, wfConfigLst, ofldUserName, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false,
                                                WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8], onBehalf, submittedFor, divisionName, lstUsers);
                                            //}
                                        }
                                        if (objDemand.UpdateFormStatus(oWeb, wfConfigLst, MainLstName, refNo, WFOrder, false, rtbForwardOthers, rtbSendBack))
                                        {
                                            formStatus = true;
                                        }

                                    }
                                }
                                else
                                {
                                    GenerateExceptionLog("Trig_AMJ_HR_Forms:: Demand_Voucher_Form::ApprovetheForm", "Query string values is wrong", "task ID values is wrong or empty");
                                }
                            }
                        }
                    }

                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "ApprovetheForm";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            return formStatus;
        }

        #endregion


        #region "Approve Form"

        public bool ApprovetheForm(string SiteURL, string MainLstName, string TaskLstName, string wfConfigLst, string CmntsLstName, string AttLibName, string FormID, string refNo,
            string TaskItemID, string WFTaskType, string ApprovalUser, string comments, FileUpload fileUploadControl, RadioButton rtbForwardOthers, RadioButton rtbSendBack,
            PeopleEditor pplcnt, bool AssignTosubmitUser)
        {

            bool formStatus = false;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {

                            SPList oLstTask = oWeb.Lists.TryGetList(TaskLstName);
                            SPList oLstForm = oWeb.Lists.TryGetList(MainLstName);
                            if (oLstTask != null && oLstForm != null)
                            {
                                FormID = Convert.ToString(oLstForm.ID);
                                //string DVTaskItemID = Convert.ToString(Request.Params["TaskItemID"]);
                                if (!string.IsNullOrEmpty(TaskItemID))
                                {
                                    //lop.Begin();
                                    SPQuery updatecamQ = new SPQuery();
                                    updatecamQ.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + TaskItemID + "</Value></Eq></Where>";
                                    SPListItemCollection TasksListitemcoll = oLstTask.GetItems(updatecamQ);
                                    if (TasksListitemcoll.Count > 0)
                                    {
                                        SPListItem oitm = TasksListitemcoll[0];
                                        oitm["Status"] = "Completed";
                                        oitm["OutCome"] = "Approved";
                                        oWeb.AllowUnsafeUpdates = true;
                                        oitm.Update();
                                        oWeb.AllowUnsafeUpdates = false;
                                        WFTaskType = Convert.ToString(oitm["WFTaskType"]);
                                        int WFOrder = 0;
                                        WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]);

                                        SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, FormID, ApprovalUser, comments, WFOrder);

                                        if (!string.IsNullOrEmpty(fileUploadControl.FileName))
                                            AddAttachement(SiteURL, AttLibName, refNo, FormID, fileUploadControl);

                                        if (rtbForwardOthers.Checked || rtbSendBack.Checked)
                                        {
                                            WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]);
                                            if (rtbForwardOthers.Checked)
                                            {
                                                createTask(oWeb, oLstForm, oLstTask, wfConfigLst, pplcnt, WFOrder, "", true, false, WFTaskType, refNo, "", "", "", "");
                                            }
                                            else if (rtbSendBack.Checked && !AssignTosubmitUser)
                                            {

                                                createTask(oWeb, oLstForm, oLstTask, wfConfigLst, pplcnt, WFOrder, "", false, true, WFTaskType, refNo, "", "", "", "");
                                            }
                                        }
                                        else if (AssignTosubmitUser)
                                        {
                                            //SPFieldUserValue user = GetSubmittedUser(SiteURL, FormID, refNo);
                                            //if (user.LookupValue.ToLower() == SPContext.Current.Web.CurrentUser.LoginName.ToLower())
                                            //{
                                            //    objDemand.UpdateFormStatus(oWeb, wfConfigLst, MainLstName, refNo, WFOrder, false);
                                            //}
                                            //else
                                            //{
                                            WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]);
                                            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, wfConfigLst, MainLstName, false, ApprovalUser, true, WFOrder);
                                            createTasktoUsers(oWeb, oLstForm, oLstTask, GetSubmittedUser(SiteURL, FormID, refNo), refNo, WFOrder, WFUser[3], AssignTosubmitUser);
                                            //}
                                        }
                                        else
                                        {
                                            WFOrder = Convert.ToInt16(oitm["WFCurrentOrder"]) + 1;
                                            string[] WFUser = CheckCurrentUserAsWFUser(oWeb, wfConfigLst, MainLstName, false, ApprovalUser, true, WFOrder);
                                            createTask(oWeb, oLstForm, oLstTask, wfConfigLst, pplcnt, Convert.ToInt32(WFUser[0]), WFUser[4], false, false, WFUser[3], refNo, WFUser[5], WFUser[6], WFUser[7], WFUser[8]);

                                            //int cnt = GetWFConfigCnt(wfConfigLst, MainLstName, SiteURL);
                                            //if (cnt != 0 && cnt == 1)
                                            //{
                                            //   objDemand.UpdateFormStatus(oWeb, wfConfigLst, MainLstName, refNo, Convert.ToInt16(oitm["WFCurrentOrder"]), false);
                                            //}
                                        }

                                        if (GetSucceededWFUser(oWeb, oLstTask, refNo).ToLower() == ApprovalUser.ToLower())
                                        {
                                            objDemand.UpdateFormStatus(oWeb, wfConfigLst, MainLstName, refNo, Convert.ToInt16(oitm["WFCurrentOrder"]), false);
                                            formStatus = true;
                                        }

                                    }
                                }
                            }
                        }
                    }

                });


            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_IT_Forms" + " :: " + "SPHelper" + " :: " + "ApprovetheForm";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
            //return FormID;
            return formStatus;
        }

        #endregion


        private string GetSucceededWFUser(SPWeb frmWeb, SPList oLstTask, string refNo)
        {
            string user = string.Empty;
            SPQuery qry = new SPQuery();
            qry.Query = "<Where><Eq><FieldRef Name='Reference_x0020_Number' /><Value Type='Text'>" + refNo + "</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";
            if (oLstTask.GetItems(qry).Count > 0)
            {
                SPFieldUserValue ofldUser = new SPFieldUserValue(frmWeb, oLstTask.GetItems(qry)[0]["AssignedTo"].ToString());
                user = ofldUser.User.Name;
            }
            return user;
        }

        public void SetUPUsers(string SiteURL, string MainLstName, string TaskLstName, string wfConfigLst, string refNo, string divisionName, int WFOrder)
        {
            try
            {
                string ApprovalUser = SPContext.Current.Web.CurrentUser.LoginName;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {

                            SPList oLstTask = oWeb.Lists.TryGetList(TaskLstName);
                            SPList oLstForm = oWeb.Lists.TryGetList(MainLstName);

                            if (oLstForm != null && oLstTask != null)
                            {

                                string[] WFUser = CheckCurrentUserAsWFUser(oWeb, wfConfigLst, MainLstName, false, ApprovalUser, true, WFOrder);
                                SPFieldUserValue ofldUserName = null;
                                if (!string.IsNullOrEmpty(WFUser[1]))
                                {
                                    ofldUserName = new SPFieldUserValue(oWeb, WFUser[1]);
                                }
                                //createTask(oWeb, oLstForm, oLstTask,"","" ,wfConfigLst, ofldUserName,refNo, Convert.ToInt32(WFUser[0]), WFUser[4],divisionName);
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "SetUPUsers";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }


        }

        public void CreateEmailAccounts(string SiteURL, string refNo, string FormID, params string[] cntrls)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        SPQuery qry = new SPQuery();
                        qry.Query = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
                        SPListItem oItem = oWeb.Lists[new Guid(FormID)].GetItems(qry)[0];
                        oItem["UserName"] = (cntrls[0] as string);
                        oItem["EmailAddress"] = (cntrls[1] as string);
                        oItem["Password"] = (cntrls[2] as string);
                        oItem.Update();
                        oWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

        private int GetWFConfigCnt(string wfConfigLst, string MainLstName, string SiteURL)
        {
            SPListItemCollection itmColl = null;
            string qry = "<Where><Eq><FieldRef Name=\"Doctype\" /><Value Type=\"Lookup\">" + MainLstName + "</Value></Eq></Where>";
            int cnt = 0;

            try
            {
                itmColl = GetSPListItems(SiteURL, wfConfigLst, qry);
                cnt = itmColl.Count;
            }
            catch (Exception)
            {
                cnt = 0;
            }
            return cnt;
        }


        public SPListItemCollection GetSPListItems(string SiteURL, string lstName, string camlQry)
        {
            SPListItemCollection oLstItemColl = null;
            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        SPList oList = oWeb.Lists.TryGetList(lstName);
                        if (oList != null)
                        {
                            SPQuery qry = new SPQuery();
                            qry.Query = camlQry;
                            oLstItemColl = oList.GetItems(qry);
                        }
                        oWeb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                oLstItemColl = null;
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "GetSPListItems";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            return oLstItemColl;
        }

        public SPListItem GetSPListItem(string SiteURL, string lstName, string camlQry)
        {

            SPListItem oLstItem = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            oWeb.AllowUnsafeUpdates = true;
                            SPList oList = oWeb.Lists.TryGetList(lstName);
                            if (oList != null)
                            {
                                SPQuery qry = new SPQuery();
                                qry.Query = camlQry;
                                oLstItem = oList.GetItems(qry)[0];
                            }
                        }
                    }

                }
                catch (Exception ex)
                {
                    oLstItem = null;
                    ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "GetSPListItem";
                    GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }
            });
            return oLstItem;
        }


        public SPListItem GetSPListItem(string SiteURL, string lstName, SPQuery qry)
        {
            SPListItem oLstItem = null;
            SPListItemCollection oLstItems = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
             {
                 try
                 {
                     using (SPSite oSite = new SPSite(SiteURL))
                     {
                         using (SPWeb oWeb = oSite.OpenWeb())
                         {
                             oWeb.AllowUnsafeUpdates = true;
                             SPList oList = oWeb.Lists.TryGetList(lstName);
                             if (oList != null)
                                 oLstItems = oList.GetItems(qry);
                             if (oLstItems.Count > 0)
                                 oLstItem = oList.GetItems(qry)[0];
                             else
                                 oLstItem = null;

                         }
                     }

                 }
                 catch (Exception ex)
                 {
                     oLstItem = null;
                     ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "SPHelper" + " :: " + "GetSPListItem";
                     GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                 }
             });
            return oLstItem;
        }

        private SPListItem GetSPListItem(string mainLstName, SPList oList)
        {
            SPListItem oLstItem = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    SPQuery qry = new SPQuery();
                    qry.Query = "<Where><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + mainLstName + "</Value></Eq></Where>";
                    oLstItem = oList.GetItems(qry)[0];
                }
                catch (Exception)
                {
                    oLstItem = null;
                }
            });
            return oLstItem;
        }

        #region "GetSubmittedUser"
        /// <summary>
        /// Get submitted user (Created By) from corresponding forms
        /// </summary>
        /// <param name="SiteURL"></param>
        /// <param name="listID"></param>
        /// <param name="refNo"></param>
        /// <returns></returns>
        public SPFieldUserValue GetSubmittedUser(string SiteURL, string listID, string refNo)
        {

            SPFieldUserValue userValue = null;
            try
            {
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        if (listID != null)
                        {
                            SPList oList = oWeb.Lists[new Guid(listID)];
                            if (oList != null)
                            {
                                SPQuery qry = new SPQuery();
                                qry.Query = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
                                qry.ViewFields = "<FieldRef Name='SubmittedFor' />";
                                SPListItem oLstItems = oList.GetItems(qry)[0];
                                userValue = new SPFieldUserValue(SPContext.Current.Web, oLstItems["SubmittedFor"].ToString());
                            }
                        }
                        oWeb.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "UserProfileInfo" + " :: " + "GetSubmittedUser";
                GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
            return userValue;
        }


        #endregion

        public void CreateLinkButton(string LinkText, string OnClickScript, GridViewRowEventArgs e, int ColumnNumber, bool EnableButton)
        {
            LinkButton lb = new LinkButton();
            lb.Text = LinkText;
            if (OnClickScript.StartsWith("javascript:"))
                lb.OnClientClick = OnClickScript;
            else
                lb.Attributes.Add("onclick", "loadFile(" + OnClickScript + ");");

            lb.Enabled = EnableButton;
            e.Row.Cells[ColumnNumber].Controls.Add((Control)lb);
        }


        public void GetApprovedUsers(string refNo, string SiteURL, string TaskLstName, GridView gvApprovers)
        {
            SPListItemCollection oItemColl = null;
            string camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
            oItemColl = GetSPListItems(SiteURL, TaskLstName, camlQry);
            DataTable dt = new DataTable();
            // dt.Columns.Add("Approved By");
            DataRow dr;

            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (oItemColl.Count > 0)
                    {
                        foreach (SPListItem oItem in oItemColl)
                        {
                            SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                            dt.Columns.Add(oItem["ID"].ToString());
                        }

                        dr = dt.NewRow();
                        int wfCnt = dt.Columns.Count;
                        int i = 0;
                        foreach (SPListItem oItem in oItemColl)
                        {
                            if (i < wfCnt)
                            {
                                SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                                if (Convert.ToString(fldUser.LookupValue).Contains("\\"))
                                {
                                    string user = Convert.ToString(fldUser.LookupValue);
                                    string[] users = user.Split('\\');
                                    int arrLenth = users.Length;
                                    if (arrLenth > 0)
                                        dr[i] = users[1];
                                    else
                                        dr[i] = users[0];
                                }
                                i++;
                            }
                        }
                        dt.Rows.Add(dr);
                        i = 0;
                        dr = dt.NewRow();
                        while (i < wfCnt)
                        {
                            dr[i] = "Approved By";
                            i++;
                        }
                        dt.Rows.Add(dr);
                        gvApprovers.DataSource = dt;
                        gvApprovers.DataBind();
                        gvApprovers.HeaderRow.Visible = false;
                    }

                }

            }

        }
    }
}
